/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ecom.beans.menuorder;

import java.util.*;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author alina
 */
@Stateless
public class MenuOrderEntityFacade implements MenuOrderEntityFacadeRemote {

    @PersistenceContext
    private EntityManager em;

    public MenuOrderEntity registerOrder(int type, double orderTotalPrice, String customerName, String deliveryAddress,
            Date orderDate, Date desiredDeliveryDate, int orderTotalSmiles) {
        try {
            
            MenuOrderEntity newOrder = new MenuOrderEntity();

            long deliveryTime = 0;
          
            newOrder.setType(type);
            newOrder.setOrderTotalPrice(orderTotalPrice);

            newOrder.setCustomerName(customerName);
            newOrder.setDeliveryAddress(deliveryAddress);
            newOrder.setOrderDate(orderDate);
            newOrder.setDesiredDeliveryDate(desiredDeliveryDate);
            Date current = new Date();
            if (desiredDeliveryDate.before(current)){
                newOrder.setStatus("delivered");
            }
            else {
                newOrder.setStatus("pending");
            }
            
            if (type == 2) { //later order
                deliveryTime = DateHelper.msDiff(desiredDeliveryDate, orderDate);
                newOrder.setDeliveryTime(deliveryTime);
            }
            else { //instant order
                //generate a random time in minutes for the delivery
                Random generator = new Random();
                int deliveryTimeInMinutes = generator.nextInt(60);
                
                //transform in miliseconds 
                deliveryTime = deliveryTimeInMinutes * 60 * 1000;
                newOrder.setDeliveryTime(deliveryTime);
            }
            
            newOrder.setOrderTotalPrice(orderTotalPrice);
            newOrder.setOrderTotalSmiles(orderTotalSmiles);

            em.persist(newOrder);
            //System.out.println("persistence effectuee");

            
            return newOrder;
            
        } catch (Exception e) {
            return null;
        }
    }
    // Add business logic below. (Right-click in editor and choose
    // "EJB Methods > Add Business Method" or "Web Service > Add Operation")
}